package scenario.implementations;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
import scenario.classes.GenericScenario;

public class GenericScenarioImpl extends GenericScenario {

	private static final int MAX_LENGHT_SIZE = 64;
	private static final int INDENT_SIZE = 4;

	@Override
	public void createUser(String userName) {
		this.setUser(new UserImpl(userName));
	}

	@Override
	public void createTargetClass(String name) {
		this.setTargetClass(new TargetClassImpl(name));
	}

	@Override
	public void createTargetEvent(String name) {
		this.setTargetEvent(new TargetEventImpl(name));

	}

	@Override
	public void generateScenario() {
		Element root = new Element("root");
		
		Element user = new Element("User");
		user.appendChild(this.getUser().getUserName());
		root.appendChild(user);
		Element targetClass = new Element("TargetClass");
		targetClass.appendChild(this.getTargetClass().getName());
		root.appendChild(targetClass);
		Element targetElement = new Element("TargetElement");
		targetElement.appendChild(this.getTargetEvent().getName());
		root.appendChild(targetElement);
		
		Document doc = new Document(root);
		try{
			Serializer serializer = new Serializer(System.out, "ISO-8859-1");
			serializer.setIndent(INDENT_SIZE);
			serializer.setMaxLength(MAX_LENGHT_SIZE);
			serializer.write(doc);
		}catch(IOException ex){
			System.err.println(ex);
		}
		
		this.setScenario(doc.toXML());
	}

	@Override
	public void saveScenario(String path) throws IOException {
		
			FileWriter file = new FileWriter(path);
			BufferedWriter buffer = new BufferedWriter(file);
			
			buffer.write(this.getScenario());
			buffer.close();
		
	}

}
